//
//  PersonInfoController.m
//  FD
//
//  Created by Yasin on 2018/10/17.
//  Copyright © 2018年 ZhiYuan Network. All rights reserved.
//

#import "PersonInfoController.h"
//view-cell
#import "BRInfoCell.h"
#import "BRInfoAvatorCell.h"

//veiw
//#import "BRPickerView.h"
#import "BRDatePickerView.h"

#import "BRTagView.h" //我的标签
#import "FDCustomAlertView.h" //1-2个人资料专用弹框


//controller
#import "FamilyMemberBirthdayViewController.h" //家庭成员生日
#import "MyLabelViewController.h" //偏好标签页面
#import "TZImagePickerController.h" //图片选择器
#import <MobileCoreServices/MobileCoreServices.h>
#import "CameraViewController.h" //自定义相机&图片裁切2019-1-12

//model
#import "PersonInfoModel.h"
#import <AWSS3/AWSS3.h> //10-27 亚马逊云存储s3

@interface PersonInfoController ()<UITableViewDataSource,UITableViewDelegate,
UITextFieldDelegate,
BRInfoAvatorCellDelegate,
TZImagePickerControllerDelegate,
UINavigationControllerDelegate,
TZImagePickerControllerDelegate,
UIImagePickerControllerDelegate,
CameraDelegate
>

/**tableView*/
@property (nonatomic,  strong) UITableView *tv1;
/**数据源*/
@property (nonatomic,  strong) NSArray *titleArr;
/**个人信息model*/
@property (nonatomic,  strong) PersonInfoModel *model;

/**我的标签*/
@property (nonatomic,  strong) BRTagView *tagView;
@property (nonatomic, strong) UIImagePickerController *imagePickerVc;
/**11-12修改头像,从相册中选择图片后就直接赋值,还传个jiba*/
@property (nonatomic, strong) UIImage *selectedImg;
/**12-8.线*/
@property (nonatomic, strong) UIView *lightGrayLineView;


@end

@implementation PersonInfoController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupView];
    
//    //取消导航条线
//    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
//    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
//
//    [self.navigationController.navigationBar setTranslucent:NO]; //设置为不透明，不写会有bug
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //请求数据
    [self loadData];
}

- (void)setupView {
    //国际化
    NSString *grzlStr = NSLocalizedString(My_personal_info, @"个人资料");
    self.navigationItem.title = grzlStr;
    self.view.backgroundColor = [UIColor whiteColor];

    self.tv1.frame = self.view.bounds;
    [self.view addSubview:self.tv1];

    self.tv1.tableHeaderView = self.lightGrayLineView;//线
    self.tv1.tableFooterView = self.tagView; //表尾
}

- (NSArray *)titleArr {
    if (!_titleArr) {
        //国际化
        
        NSString *ncStr = NSLocalizedString(NickName, @"昵称");
        NSString *sjhStr = NSLocalizedString(PhoneNumber, @"手机号");
        NSString *xbStr = NSLocalizedString(Gender, @"性别");
        NSString *srStr = NSLocalizedString(Birthday, @"生日");
        NSString *jtcyStr = NSLocalizedString(FamilyMember, @"家庭成员生日");

        _titleArr = @[@"头像",ncStr,sjhStr,xbStr,srStr,jtcyStr];
    }
    return _titleArr;
}
- (UIView *)lightGrayLineView {
    if (!_lightGrayLineView) {
        _lightGrayLineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10)];
        _lightGrayLineView.backgroundColor = kMainLightGrayColor;
    }
    return _lightGrayLineView;
}


- (BRTagView *)tagView {
    if (!_tagView) {
        _tagView = [[BRTagView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 60)];
        
        __weak typeof(self) weakSelf = self;
        _tagView.clickMyTagViewBlock = ^{
            FDLog(@"点击了 我的标签");
            MyLabelViewController *labelVC = [MyLabelViewController new];
            [weakSelf.navigationController pushViewController:labelVC animated:YES];
        };
    }
    return _tagView;
}

- (UITableView *)tv1 {
    if (!_tv1) {
        _tv1 = [[UITableView alloc] initWithFrame:CGRectZero style:(UITableViewStylePlain)];
        _tv1.delegate = self;
        _tv1.dataSource = self;
        
        //注册cell
        [_tv1 registerClass:[BRInfoCell class] forCellReuseIdentifier:@"BRInfoCell"]; //头像
        [_tv1 registerClass:[BRInfoAvatorCell class] forCellReuseIdentifier:@"BRInfoAvatorCell"];
        [_tv1 registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"]; //系统
        
        _tv1.backgroundColor = kMainLightGrayColor; //灰色背景
        //取消线
        _tv1.separatorStyle = UITableViewCellSelectionStyleNone;
        _tv1.scrollEnabled = NO;
    }
    return _tv1;
}


#pragma mark - 代理 UITableViewDataSource,
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.titleArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    if (indexPath.row == 0) { //头像cell
        BRInfoAvatorCell *avatorCell = [tableView dequeueReusableCellWithIdentifier:@"BRInfoAvatorCell"];
        avatorCell.delegate = self;
        
        //有个bug:1.图片上传成功了,但是更新不了; 2.太耗时.
        //选择图片之后,直接进行赋值。
        if (self.selectedImg) {
            avatorCell.iconIv.image = self.selectedImg;
        }else {
            [avatorCell.iconIv sd_setImageWithURL:[NSURL URLWithString:self.model.head]];//设置头像
        }
        
        return avatorCell;
    }else {
        BRInfoCell *cell2 = [tableView dequeueReusableCellWithIdentifier:@"BRInfoCell"];
        cell2.titleLabel.text = self.titleArr[indexPath.row];
        cell2.textField.tag = indexPath.row; //添加tag值,后面控制是否弹出键盘
        //国际化
        NSString *qxztxStr = NSLocalizedString(PutYouNickName, @"请输入昵称");
        NSString *qtxsjhStr = NSLocalizedString(Put_your_phone, @"请填写手机号");
        NSString *qxzxbStr = NSLocalizedString(PleaseSelectGender, @"请选择性别");
        NSString *manStr = NSLocalizedString(L_Nan, @"男");
        NSString *nvStr = NSLocalizedString(L_Nv,  @"女");
    
        NSString *qxzsrStr = NSLocalizedString(Tips_PleaseSelectDirthday,  @"请选择生日");

//        self.model.sex = @(-1); //2019-2-19未知
        
        cell2.textField.delegate = self; //统一设置代理
        if (indexPath.row == 1) {
            cell2.textField.placeholder = qxztxStr;//@"请输入昵称"
            cell2.textField.text = self.model.nickname;
            [cell2 brInfocellHideRightArrowIv];//1-2隐藏右箭头

        }else if (indexPath.row == 2) {
            cell2.textField.placeholder = qtxsjhStr; //@"请填写手机号"
            cell2.textField.text = self.model.phone;
            
        }else if (indexPath.row == 3) {
            cell2.textField.placeholder = qxzxbStr; //请选择性别
            if ([self.model.sex isEqualToNumber:@0]) { //男
                cell2.textField.text = manStr;
            }else if([self.model.sex isEqualToNumber:@(1)]) {
                cell2.textField.text = nvStr;
            }else if ([self.model.sex isEqualToNumber:@(-1)]){
                cell2.textField.text = @"未知";
            }
        }else if (indexPath.row == 4) {
            cell2.textField.placeholder = qxzsrStr; //@"请选择生日"
            cell2.textField.text = self.model.birthdayStr;
        }else if(indexPath.row == 5){ //家庭成员生日
            
        }
        return cell2;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 100;
    }else{
        return 50;
    }
}

#pragma mark - 12-5 家庭成员身日点击范围扩大
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0) { //0 头像
        
    }else if(indexPath.row == 1) { //1.昵称
        
    }else if (indexPath.row == 2) { //2.手机号
        
    }else if (indexPath.row == 3) { //3.性别
        
    }else if (indexPath.row == 4) { //4.生日
        
    }else if (indexPath.row == 5) { //5.家庭成员生日
        [self skipToFamilyMemberBirthdayVC];
    }
}

#pragma mark - 点击跳转到我的标签

#pragma mark - 代理 UITableViewDelegate

#pragma mark - 代理 UITextFieldDelegate

//填写姓名可以输入文字，其他的都是弹框
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField.tag == 1) {
        [textField resignFirstResponder];
    }
    return YES;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    //    if (textField.tag == 1) { //填写姓名可以输入文字，其他的都是弹框
    //        [textField addTarget:self action:@selector(handlerTextFieldEndEdit:) forControlEvents:(UIControlEventTouchUpInside)];
    //        return YES;
    //    }else {
    //        [self.view endEditing:YES];
    //        [self handlerTextFieldSelect:textField];
    //        return NO;
    //    }
    
    //都不让输入
    [self.view endEditing:YES];
    [self handlerTextFieldSelect:textField];
    return NO;
}

- (void)handlerTextFieldEndEdit:(UITextField *)textField
{
    
}

#pragma mark -处理业务逻辑:修改昵称、手机号、性别、生日......
- (void)handlerTextFieldSelect:(UITextField *)textField
{
   
    //弹框
    if (textField.tag == 1) { //修改昵称
        [self alertTextVCWithType:0];
        
    }else if (textField.tag == 2) { //修改手机号
        [self alertTextVCWithType:1];
        
    }else if (textField.tag == 3) { //选择性别
//        //国际化除了这个是@“男”、@“女” 其他的都是先生女士

        NSString *manStr = @"Male";
        NSString *nvStr = @"Female";
        if ([NSString rb_ChineseLanguage]) {
            manStr = @"男";
            nvStr = @"女";
        }
        
//        NSString *manStr = NSLocalizedString(Home_Man, @"先生");
//        NSString *nvStr = NSLocalizedString(Home_Woman,  @"女士");
        [FDCustomAlertView showAlertWithTitleArr:@[manStr,nvStr] complectionBlock:^(NSInteger index, NSString * _Nonnull selectValue) {
            
            NSNumber *sex = @(0);
            if ([selectValue isEqualToString:nvStr]) sex = @(1);
            //调接口
            [self requestUpdateSex:sex];
        }];
        
    }else if(textField.tag == 4) { //选择出生日期
        NSDate *minDate = [NSDate br_setYear:1900 month:1 day:1];
        NSDate *maxDate = [NSDate date];
        //国际化
        NSString *csrqStr = NSLocalizedString(Birthday, @"出生日期");
        
        //12-3判断 服务器返回日期过大,导致崩溃问题，。
        [BRDatePickerView showDatePickerWithTitle:csrqStr dateType:BRDatePickerModeYMD defaultSelValue:@"2000-1-1" minDate:minDate maxDate:maxDate isAutoSelect:NO themeColor:nil resultBlock:^(NSString *selectValue) {
            
            textField.text = selectValue;
            
            NSNumber *timestamp = [NSString timeStampFromDateStr:selectValue];
            [self requestUpdateBirthday:timestamp];
            
        } cancelBlock:^{
            NSLog(@"点击了背景或取消按钮");
        }];
    }else if (textField.tag == 5) { //跳转到家庭成员生日页面
        [self skipToFamilyMemberBirthdayVC];
    }
}

- (void)skipToFamilyMemberBirthdayVC {
    FamilyMemberBirthdayViewController *birthdayVC = [[FamilyMemberBirthdayViewController alloc] init];
    [self.navigationController pushViewController:birthdayVC animated:YES];
}

#pragma mark - 弹框输入

/**
 弹框
 @param type 0 修改昵称 1 修改手机号
 */
- (void)alertTextVCWithType:(NSInteger)type{
    
    NSString *msg = NSLocalizedString(ModifyNickName, @"修改昵称");
    if (type == 1) {
        msg = NSLocalizedString(ModifyPhone, @"修改手机号");
    }
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"" message:msg preferredStyle:(UIAlertControllerStyleAlert)];
    
    NSString *qxStr = NSLocalizedString(Cancel, @"取消");
    NSString *qdStr = NSLocalizedString(Sure, @"确定");

    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:qxStr style:(UIAlertActionStyleCancel) handler:nil];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:qdStr style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        //取出输入框
        UITextField *tf = alertVC.textFields[0];
//        tf.text = self.model.phone ? :@"没有手机号";
        
        //调接口
        if (type == 1) { //修改手机号
            [self requestUpdatePhone:tf.text];
            
        }else { //修改昵称
            [self requestUpdateNickname:tf.text];
        }
    }];

    //2019-1-19修改按钮文字文字按颜色
    [self xxChangeUIAlertActionTextColorToBalckWithAction:cancelAction];
    [self xxChangeUIAlertActionTextColorToBalckWithAction:sureAction];
    
    [alertVC addAction:cancelAction];
    [alertVC addAction:sureAction];
    [alertVC addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        if (type == 1) {
            
            textField.text = self.model.phone ? : @"";
        }else {
            textField.text = self.model.nickname ? :@"";
        }
    }];
    
    [self presentViewController:alertVC animated:YES completion:nil];
}

//!!!!:1-19修改 UIAlertAction 按钮文字颜色
- (void)xxChangeUIAlertActionTextColorToBalckWithAction:(UIAlertAction *)action {
    //❌
//    if ([action valueForKey:@"titleTextColor"]) {
//        [action setValue:[UIColor blackColor] forKey:@"titleTextColor"];
//    }
    
    //❌
//    if ([action valueForKey:@"_titleTextColor"]) {
//        [action setValue:[UIColor blackColor] forKey:@"_titleTextColor"];
//    }
    //✅
//    [UIColor blackColor];
    [action setValue:kLightGrayTextColor forKey:@"_titleTextColor"];
}

//回收键盘
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self.view endEditing:YES];
}
#pragma mark - 头像点击
- (void)brInfoAvatorCellDidClockAvaorAction:(UIImageView *)iv
{
    //国际化
    NSString *pzStr = NSLocalizedString(TakePhoto, @"拍照");
    NSString *cxczxzStr = NSLocalizedString(SelectFromAlbum, @"从相册选择");

    [FDCustomAlertView showAlertWithTitleArr:@[pzStr,cxczxzStr] complectionBlock:^(NSInteger index, NSString * _Nonnull selectValue) {
        if (index==0) {
//            [self pushImagePickerController];
            [self paiZhaoViewController];
        }else {
            [self pushTZImagePickerController];
        }
    }];
}

//- (void)brInfoAvatorCellDidClockAvaorAction:(UIImageView *)iv
//{
//    NSLog(@"当前线程:%@",[NSThread currentThread]);
//
//    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"" message:@"修改头像" preferredStyle:(UIAlertControllerStyleActionSheet)];
//    //国际化
//    NSString *pzStr = NSLocalizedString(TakePhoto, @"拍照");
//    UIAlertAction *paiZhao = [UIAlertAction actionWithTitle:pzStr style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
//
//        //模拟器，暂时不能选择图片，先用本地图片代替，。
////        {
////            //长传一个假本地图片
////            UIImage *tempImg = [UIImage imageNamed:@"冬天.jpg"];
////            //转图片
////            NSData *imgData = UIImageJPEGRepresentation(tempImg, 1.0);
////            //获取亚马逊云存储图片名字，并上传图片
////            [self requestAmazonS3AuthoAndUpLoadData:imgData];
////        }
//
//        [self pushImagePickerController];
//    }];
//
//    NSString *cxczxzStr = NSLocalizedString(SelectFromAlbum, @"从相册选择");
//    NSString *qxStr = NSLocalizedString(Cancel, @"取消");
//
//    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:cxczxzStr style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
//        [self pushTZImagePickerController];
//    }];
//
//    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:qxStr style:(UIAlertActionStyleCancel) handler:nil];
//
//    [alertVC addAction:paiZhao];
//    [alertVC addAction:photoAction];
//    [alertVC addAction:cancelAction];
//
//    //
//    [self presentViewController:alertVC animated:YES completion:nil];
//}



#pragma mark - 请求数据 ❗️❗️❗️❗️❗️❗️
- (void)loadData {
    [FDHttpAPi requestUserPersonMsgSuccessBlock:^(id responseObjc) {
        FDLog(@"用户个人信息：%@",responseObjc);
        
        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:SUCCESS]) { //请求成功解析数据
            NSDictionary *data = responseObjc[@"data"];
            
            self.model = [PersonInfoModel mj_objectWithKeyValues:data];
            FDLog(@"%@",self.model);
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tv1 reloadData];
                //更新标签
                [self.tagView updateTags:self.model.label];
            });
            
        }else { //toast
            [JRToast showWithText:responseObjc[describe]];
        }
        
    } failBlock:^(NSError *error) {
        FDLog(@"%@",[error localizedDescription]);
    }];
}
//修改昵称
- (void)requestUpdateNickname:(NSString *)nickname {
    [FDHttpAPi requestUserUpdateNickname:nickname successBlock:^(id responseObjc) {

        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:SUCCESS]) {
            [self xxshowModifySuccessToast];
            
            //重新调用一次接口
            [self loadData];
        }else {
            [JRToast showWithText:responseObjc[describe]];
        }
    } failBlock:^(NSError *error) {
        FDLog(@"%@",[error localizedDescription]);
    }];
}
//修改手机号
- (void)requestUpdatePhone:(NSString *)phone {
    [FDHttpAPi requestUserUpdatePhone:phone successBlock:^(id responseObjc) {
        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:SUCCESS]) {//修改成功
            [self xxshowModifySuccessToast];
            //重新调用一次接口
            [self loadData];
        }else {
            [JRToast showWithText:responseObjc[describe]];
        }
    } failBlock:^(NSError *error) {
        FDLog(@"%@",[error localizedDescription]);
    }];
}

//修改性别 :0男 1女
- (void)requestUpdateSex:(NSNumber *)sex {
    [FDHttpAPi requestUserUpdateSex:sex successBlock:^(id responseObjc) {
        NSString *event = responseObjc[@"event"];

        if ([event isEqualToString:SUCCESS]) {//修改成功
            [self xxshowModifySuccessToast];
            //重新调用一次接口
            [self loadData];
        }else {
            [JRToast showWithText:responseObjc[describe]];
        }
    } fialBlock:^(NSError *error) {
//        FDLog(@"%@",[error localizedDescription]);
        FDLog(@"%@",[error localizedDescription]);
    }];
}

//修改生日
- (void)requestUpdateBirthday:(NSNumber *)timestamp {
    [FDHttpAPi requestUserUpdateBirthday:timestamp successBlock:^(id responseObjc) {
        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:SUCCESS]) {//修改成功
            [self xxshowModifySuccessToast];
            //重新调用一次接口
            [self loadData];
        }else {
            [JRToast showWithText:responseObjc[describe]];
        }
    } failBlock:^(NSError *error) {
        FDLog(@"%@",[error localizedDescription]);
    }];
}

#pragma mark - 2019-2-12
- (void)xxshowModifySuccessToast {
    [JRToast showWithText:NSLocalizedString(ToastModifySuccess, @"修改成功")];
}



//修改头像

#pragma mark - fjafj
- (UIImagePickerController *)imagePickerVc {
    if (_imagePickerVc == nil) {
        _imagePickerVc = [[UIImagePickerController alloc] init];
        _imagePickerVc.navigationBar.barTintColor = self.navigationController.navigationBar.barTintColor;
        _imagePickerVc.navigationBar.tintColor = self.navigationController.navigationBar.tintColor;
        _imagePickerVc.delegate = self;
        UIBarButtonItem *tzBarItem, *BarItem;
        if (@available(iOS 9, *)) {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]];
            BarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]];
        } else {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedIn:[TZImagePickerController class], nil];
            BarItem = [UIBarButtonItem appearanceWhenContainedIn:[UIImagePickerController class], nil];
        }
        NSDictionary *titleTextAttributes = [tzBarItem titleTextAttributesForState:UIControlStateNormal];
        [BarItem setTitleTextAttributes:titleTextAttributes forState:UIControlStateNormal];
        
    }
    return _imagePickerVc;
}

#pragma mark - 图片选择器 三方
#pragma mark - UIImagePickerController

- (void)takePhoto {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
        // 无相机权限 做一个友好的提示
        [self permissionAlert];
        
    } else if (authStatus == AVAuthorizationStatusNotDetermined) {
        // fix issue 466, 防止用户首次拍照拒绝授权时相机页黑屏
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if (granted) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self takePhoto];
                });
            }
        }];
        // 拍照之前还需要检查相册权限
    } else if ([PHPhotoLibrary authorizationStatus] == 2) { // 已被拒绝，没有相册权限，将无法保存拍的照片
        [self permissionAlert];
        
    } else if ([PHPhotoLibrary authorizationStatus] == 0) { // 未请求过相册权限
        [[TZImageManager manager] requestAuthorizationWithCompletion:^{
            [self takePhoto];
        }];
    } else {
//        [self pushImagePickerController];
        
        [self paiZhaoViewController];
    }
}





//权限弹框
- (void)permissionAlert {
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
    [alertVc addAction:cancel];
    [self presentViewController:alertVc animated:YES completion:nil];
}


//!!!!:拍照上传
- (void)pushImagePickerController {
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        self.imagePickerVc.sourceType = sourceType;
        NSMutableArray *mediaTypes = [NSMutableArray array];
        
        [mediaTypes addObject:(NSString *)kUTTypeImage];
        
        if (mediaTypes.count) {
            _imagePickerVc.mediaTypes = mediaTypes;
        }
        [self presentViewController:_imagePickerVc animated:YES completion:nil];
    } else {
        [JRToast showWithText:@"模拟器中无法打开照相机,请在真机中使用"];
        NSLog(@"模拟器中无法打开照相机,请在真机中使用");
    }
}

- (void)paiZhaoViewController {
    CameraViewController *camerVC = [[CameraViewController alloc] init];
    camerVC.delegate = self;
    [self presentViewController:camerVC animated:YES completion:nil];
}


//!!!!:从相册中选择上传
- (void)pushTZImagePickerController {
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 columnNumber:4 delegate:self pushPhotoPickerVc:YES];

    //1-2图片裁切
    imagePickerVc.allowCrop = YES;
    imagePickerVc.needCircleCrop = YES;
    
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        NSLog(@"111111111111111");
        UIImage *img = [photos firstObject];
        self.selectedImg = img; //直接显示®
        NSData *imgData = UIImageJPEGRepresentation(img, 1.0);
        [self requestAmazonS3AuthoAndUpLoadData:imgData];
    }];
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey, id> *)info{
    FDLog(@"拍照回调用:%@:",info);

    //手动消失
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    
    UIImage *pzImg = info[UIImagePickerControllerOriginalImage];
    NSData *imgData = UIImageJPEGRepresentation(pzImg, 0.5);
    
    //更新页面
    self.selectedImg = pzImg; //直接显示®

    //上传
    [self requestAmazonS3AuthoAndUpLoadData:imgData];
}


- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    FDLog(@"拍照结束");
    [picker dismissViewControllerAnimated:YES completion:nil];
}



//选取照片的回调
- (void)CameraTakePhoto:(UIImage *)image
{
    FDLog(@"拍照裁切后的图片:%@",image);
    FDLog(@"拍照回调用:");
    NSData *imgData = UIImageJPEGRepresentation(image, 0.5);
    //更新页面
    self.selectedImg = image; //直接显示®
    
    //上传
    [self requestAmazonS3AuthoAndUpLoadData:imgData];
}


#pragma mark - 亚马逊云存储S3
//!!!!:获取亚马逊云存储数据授权信息
- (void)requestAmazonS3AuthoAndUpLoadData:(NSData *)picData{
    [FDHttpAPi requestAuthAmazonS3CloudStorageSuccessBlock:^(id responseObjc) {
        FDLog(@"11111:%@",responseObjc);
        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:SUCCESS]) { //请求成功，解析数据
            //资源名：必须使用次名字命名图片，显示的的时候直接拼接上图片前缀
            NSString *objectKey = responseObjc[@"data"][@"objectKey"];
            
            //请求成功之后 ，拿到key,调用亚马逊s3接口上传图片。
            [self uploadData:picData updataPicName:objectKey];
            
        }else {
            [JRToast showWithText:responseObjc[describe]];
        }
    } failureBlock:^(NSError *error) {
        FDLog(@"22222:%@",error);
    }];
}
//!!!!:上传图片
- (void)uploadData:(NSData *)data updataPicName:(NSString *)picName
{

    [MBProgressHUD fd_showHUDToView:self.view];//菊花
    
    //Create the completion handler for the transfer
    AWSS3TransferUtilityUploadCompletionHandlerBlock completionHandler = ^(AWSS3TransferUtilityUploadTask *task, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (error) {
                
                [JRToast showWithText:NSLocalizedString(ToastUploadFailed, @"上传失败")];
                [MBProgressHUD fd_hideHUDFromView:self.view]; //隐藏菊花
            } else {
                //先
                [JRToast showWithText:NSLocalizedString(ToastUploadSuccess, @"上传成功")];
                [MBProgressHUD fd_hideHUDFromView:self.view]; //隐藏菊花
                
                //有bug:换个思路,图片是我传上去的,干脆我自己在本地改算了。
                [self.tv1 reloadData];
                
                //调接口:更新头像
                [self requestModifyTouXiang:picName];
            }
        });
    };
    
    //Create the TransferUtility expression and add the progress block to it.
    //This would be needed to report on progress tracking
    AWSS3TransferUtilityUploadExpression *expression = [AWSS3TransferUtilityUploadExpression new];
    expression.progressBlock = ^(AWSS3TransferUtilityTask *task, NSProgress *progress) {
        dispatch_async(dispatch_get_main_queue(), ^{
            
        });
    };
    
    AWSS3TransferUtility *transferUtility = [AWSS3TransferUtility defaultS3TransferUtility];
    [[transferUtility uploadData:data
                          bucket:FDAWSS3BucketName
                             key:picName
                     contentType:@"image/jpge"
                      expression:expression
               completionHandler:completionHandler] continueWithBlock:^id(AWSTask *task) {
        if (task.error) {
            NSLog(@"Error: %@", task.error);
        }
        if (task.result) {
           
        }
        return nil;
    }];
}

//!!!!:修改头像接口 只是把图片名传给服务器而已。
- (void)requestModifyTouXiang:(NSString *)touXiangStr {
    [FDHttpAPi requestUserUpdateTouXiangStr:touXiangStr successBlock:^(id responseObjc) {
        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:SUCCESS]) {
            FDLog(@"更改图头像成功");
        }else {
            [JRToast showWithText:describe];
        }
    } failBlock:^(NSError *error) {
        FDLog(@"%@",[error localizedDescription]);
    }];
}





@end
